package com.luckyframe.project.jmeter.jmeterNode;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public enum  JmeterNodeDeferredResultHolder {

    INSTANCE;


    Map<Long, List<DeferredResult>>  results=new ConcurrentHashMap<>();


    public void nodeStatusChanged(Long nodeId,Integer status){

        List<DeferredResult> deferredResults = results.get(nodeId);
        if(CollectionUtils.isNotEmpty(deferredResults)){
            for (DeferredResult deferredResult : deferredResults) {
                Map map=new HashMap();
                map.put("id",nodeId);
                map.put("status",status);
                deferredResult.setResult(map);
            }
        }

        results.put(nodeId,new ArrayList<>());
    }


    public void bufferDeferredResult(Long id,DeferredResult deferredResult){

        List<DeferredResult> deferredResults = results.get(id);
        if(deferredResults==null){
            deferredResults=new ArrayList<>();

            deferredResults.add(deferredResult);
        }else{
            results.get(id).add(deferredResult);
        }
        results.put(id,deferredResults);
    }

    public void remoteResult(Long id, DeferredResult objectDeferredResult) {

        List<DeferredResult> deferredResults = results.get(id);
        if(CollectionUtils.isNotEmpty(deferredResults)){
            deferredResults.remove(objectDeferredResult);
        }
    }
}
